package com.boot.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.boot.common.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

@Component
public class MyBlockException implements BlockExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(MyBlockException.class);
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s, BlockException e) throws Exception {
        logger.info("Custom block exception handler triggered");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        Result build = Result.build(500, s + "被sentinel限制了");
        String json = new ObjectMapper().writeValueAsString(build);
        writer.write(json);
        writer.flush();
        writer.close();
    }
}
